package com.mapler.service;

import com.mapler.model.SModel;
import com.mapler.model.UAModel;
import com.mapler.ui.Action;
import com.mapler.utility.Util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Keys;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Worker {

    private String getLocation(WebDriver driver, String location) {
        List<WebElement> elements = driver.findElements(By.tagName("tr"));
        for (WebElement elementLink : elements) {
            List<WebElement> thEles = elementLink.findElements(By.tagName("th"));
            for (WebElement thEle : thEles) {
                if (thEle.getText().contains(location)) {
                    List<WebElement> tdEles = elementLink.findElements(By.tagName("td"));
                    for (WebElement tdEle : tdEles) {
                        return tdEle.getText();
                    }
                }
            }
        }
        return "";
    }

    public boolean readFile(WebDriver driver, String state, String city) {
        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("C:\\irobot\\craigslist_city\\city.txt"));
            boolean look = false;
            if (!state.isEmpty()) {
                while ((sCurrentLine = br.readLine()) != null) {
                    if(sCurrentLine.toLowerCase().contains("-"+state.toLowerCase())){
                        look = true;
                        continue;
                    } else if(look && sCurrentLine.toLowerCase().startsWith("-")){
                        break;
                    }
                    if(look){
                        if(sCurrentLine.toLowerCase().contains(city.toLowerCase())){
                            driver.get(sCurrentLine.split("\\|")[1]);
                            return true;
                        }
                    }
                }
            } else {
                while ((sCurrentLine = br.readLine()) != null) {
                    if(!sCurrentLine.toLowerCase().startsWith("-") 
                            && sCurrentLine.toLowerCase().contains(city.toLowerCase())){
                        driver.get(sCurrentLine.split("\\|")[1]);
                        return true;
                    }
                }
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }
    
    private void runfile(){
        try {
            URL uri = getClass().getResource("/com/mapler/resources/auto.bat");            
            String CMD = "cmd /c start "+uri.toString().replace("file:/", "");
            System.out.println("uri"+CMD);
            Runtime.getRuntime().exec(CMD);
            //CMD = "taskkill /IM cmd.exe";
            //Runtime.getRuntime().exec(CMD);
            //String CMD = "cmd /c start D:\\comp\\auto.bat";            
            //Process process = Runtime.getRuntime().exec(CMD);
            //BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));            
             //CMD = "taskkill /IM cmd.exe";
             //Runtime.getRuntime().exec(CMD);
            
        } catch (Exception ex) {
            Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
        }
   
    }
    public static void Xmain(String ss[]) {
        Worker worker = new Worker();
        try {
            worker.runfile();
            if(true) return;
            /*SModel sModel = new SModel();
            sModel.setDriver("FF");
            WebDriver driver = Util.getDriver(sModel);
            UAModel uam = new UAModel();
            uam.setForwardEmail("skyroproject8@gmail.com");
            uam.setForwardEmailPass("dhaka100");
            MailRunner mailRunner = new MailRunner(null, sModel, uam);
            mailRunner.checkEmail(driver);
            */    
           // URL url = getClass().getResource("/xxx/xxx/xxx/services.xml");
            String CMD = "cmd /c start D:\\comp\\auto.bat";            
            Process process = Runtime.getRuntime().exec(CMD);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));            
             CMD = "taskkill /IM cmd.exe";
             Runtime.getRuntime().exec(CMD);
            // Read command standard output            
           /* String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println("Line ::: "+s);
            } */
            /*Util.connect("23.19.41.10", "emilyfplacencia", "ixeN4Ch");
            SModel sModel = new SModel();
            sModel.setDriver("FF");
            WebDriver driver = Util.getDriver(sModel);
            Thread th1 = new Thread(new JobClickPVA(driver),"T1"); 
            driver = Util.getDriver(sModel);
            Thread th2 = new Thread(new JobClickPVA(driver),"T1");
            th1.start(); 
            th2.start();
            */
            //d.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");// new tab open
            //d.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"w");// close the tab
            /*good code Util.connect("23.19.41.10", "emilyfplacencia", "ixeN4Ch");
            //driver.get("http://geoip.hidemyass.com/");
            driver.get("http://ipaddress.com/");
            String state = worker.getLocation(driver, "State:");
            String city = worker.getLocation(driver, "City:");
            if (state.isEmpty() || city.isEmpty()) {
                //log message here ...
                return;
            }
            worker.readFile(driver, state, city);
            Util.byClickTag(driver, "post");
            
            //driver.findElement(By.xpath("//input[contains(@value,'jo')]")).click();
            driver.findElement(By.xpath("//input[@value='jo']")).click();
            driver.findElement(By.xpath("//button[@name='go']")).click();
            driver.findElement(By.xpath("//button[@value='24']")).click();
            * 
            * end of good code
            * 
            /*WebElement coEle = null;
             driver.get("http://www.craigslist.org/about/sites");
             List<WebElement> boxEles = driver.findElements(By.className("colmask"));
             for (WebElement boxEle : boxEles) {
             coEle = boxEle;
             break;
             }
             coEle.findElement(By.xpath("//a[contains(.,'"+city.toLowerCase()+"')]")).click();
             */
            //Util.disConnect("23.19.41.10", "emilyfplacencia", "ixeN4Ch");
            //.setProxyServer("192.168.202.100");
            //sModel.setProxyPort(8080);
            //sModel.setProxyType(true);
            // sModel.setBrowserProxy(true);

            //Util.sendKeysById(driver, "gs_htif0", "craigslist");
        } catch (Exception ex) {
            Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String s[]) {
        ArrayList<String> locations = new ArrayList<String>();
        locations.add("Mithun");
        locations.add("prantoor");
        
        System.out.println(locations.contains("Mithun"));
        //FirefoxDriver driver = new FirefoxDriver();
        //WebDriver driver = new FirefoxDriver();
        //InternetExplorerDriver driver = new InternetExplorerDriver();
        // driver.get("https://accounts.craigslist.org/login");
        //driver.get("http://bangladesh.craigslist.org/cas/");
        //driver.get("https://accounts.craigslist.org/");

        /*driver.get("https://post.craigslist.org/k/ytmjz5gV4xGKeasy--FJ2g/d6lL9?s=edit");
        WebElement ele = driver.findElement(By.xpath("//section[@class='contents']"));
        String location = ele.getText().trim()
                .replace("log in to your account", "")
                .replace("(Apply for Account)", "").trim();
        String[] locations = location.split(">");
        System.out.println("locations "+locations.length);
        if(locations.length == 4) {
            System.out.println(locations[0].replace("craigslist", "").trim());
        } else {
           System.out.println(locations[3].replace("craigslist", "").trim()); 
        }*/
        /*WebElement email = driver.findElement(By.id("inputEmailHandle"));
        email.sendKeys("korinthas@gmail.com");

        WebElement pass = driver.findElement(By.id("inputPassword"));
        pass.sendKeys("we0123456789");

        List<WebElement> elements = driver.findElements(By.tagName("button"));
        for (WebElement elementLink : elements) {
            if (elementLink.getAttribute("type") != null
                    && elementLink.getAttribute("type").equalsIgnoreCase(
                    "submit")) {
                elementLink.submit();
                break;
            }
        }
        driver.get("http://post.craigslist.org/c/bhm/J/ofc/none/x");*/

        /*List<WebElement> elements = driver.findElementsByTagName("a");
         for (WebElement elementLink : elements) {
         if (elementLink.getAttribute("href") != null
         && elementLink.getAttribute("href").contains(
         "https://post.craigslist.org/")) {
         elementLink.click();
         break;
         }
         }*/
        /*elements = driver.findElementsByTagName("input");
         for (WebElement elementLink : elements) {
         if (elementLink.getAttribute("value") != null
         && elementLink.getAttribute("value")
         .equalsIgnoreCase("cas")) {
         elementLink.click();
         break;
         }
         }

         WebElement element = driver.findElementById("w");
         if (element == null)
         return;
         element.click();

         element = driver.findElementById("m2");
         if (element == null)
         return;
         element.click();

         elements = driver.findElementsByTagName("button");
         for (WebElement elementLink : elements) {
         if (elementLink.getAttribute("value") != null
         && elementLink.getAttribute("value").equalsIgnoreCase(
         "Continue")) {
         elementLink.submit();
         break;
         }
         }

         elements = driver.findElementsByTagName("div");
         String location = "";
         for (WebElement elementLink : elements) {
         if (elementLink.getAttribute("class") != null
         && elementLink.getAttribute("class").equalsIgnoreCase(
         "contents")) {
         location = elementLink.getText();
         break;
         }
         }

         String loc = "";
         if (!location.isEmpty()) {
         String[] locations = location.split(">");
         if (locations.length == 5) {
         loc = locations[2];
         } else {
         loc = locations[1];
         }
         System.out.println(location + "::" + loc);
         }

         int count = 1;
         String postTitle = "Title";
         int postAge = 12;
         String postLoc = loc;
         String postDesc = "description";

         elements = driver.findElementsByTagName("input");
         for (WebElement elementLink : elements) {
         if (elementLink.getAttribute("type") != null
         && elementLink.getAttribute("type")
         .equalsIgnoreCase("text")) {
         if (count == 1) {
         elementLink.sendKeys(postTitle);
         } else if (count == 2) {
         elementLink.sendKeys("" + postAge);
         } else if (count == 3) {
         elementLink.sendKeys("" + postLoc);
         } else if (count == 6) {
         elementLink.sendKeys("" + postDesc);
         }
         count++;
         }
         }

         count = 1;
         elements = driver.findElementsByTagName("textarea");
         for (WebElement elementLink : elements) {
         if (count == 1) {
         elementLink.sendKeys("" + postDesc);
         break;
         }
         }*/

        /* Final submit */
        /*elements = driver.findElementsByTagName("button");
         for (WebElement elementLink : elements) {
         if (elementLink.getAttribute("value") != null
         && elementLink.getAttribute("value").equalsIgnoreCase(
         "Continue")) {
         elementLink.submit();
         break;
         }
         }*/
        System.out.println("click found:::");
        // WebElement eleEmail = driver.findElement(By.id("inputEmailHandle"));
        // WebElement elePass = driver.findElement(By.id("inputPassword"));
        // eleEmail.sendKeys("test@yahoo.com");
        // elePass.sendKeys("password");
    }
}
